package com.kawins.spring.config;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContext;

/**
 * @author rankai
 *         createTime 2018-01-2018/1/25 17:23
 */
public class EnvConstant {

    private static final Logger log = LoggerFactory.getLogger(EnvConstant.class);

    public static final String DEV_MYSQL = "dev-mysql";

    public static final String TEST_MYSQL = "test-mysql";

    public static final String PRO_MYSQL = "pro-mysql";

    public static final String DEV_ORACLE = "dev-oracle";

    public static final String TEST_ORACLE = "test-oracle";

    public static final String PRO_ORACLE = "pro-oracle";

    public static String selectEnv(String parameter) {
        String env;
        if (parameter.charAt(0) == '$' && parameter.charAt(1) == '{' &&
                parameter.charAt(parameter.length() - 1) == '}') {
            parameter = parameter.substring(2, parameter.length() - 1);
            String[] split = parameter.split(":");
            env = System.getenv(split[0]);
            if (env == null) {
                if (split.length != 1) {
                    env = split[1];
                }
            }
        } else {
            env = parameter;
        }
        if (StringUtils.isBlank(ConfigKit.ENV)) {
            log.info(">>>>>>>>>>>>>>> this web env is [{}] <<<<<<<<<<<<<<<", env);
            ConfigKit.ENV = env;
        }
        return env;
    }

    public static String selectEnv() {
        ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        String parameter = servletContext.getInitParameter("spring.profiles.active");
        parameter = parameter == null ? servletContext
                .getInitParameter("spring.profiles.default") : parameter;
        String env = selectEnv(parameter);
        if (StringUtils.isBlank(ConfigKit.ENV)) {
            log.info(">>>>>>>>>>>>>>> this web env is [{}] <<<<<<<<<<<<<<<", env);
            ConfigKit.ENV = env;
        }
        return env;
    }
}
